<template>
	<view class="wrapper">
		<!-- 认证表单 -->
		<view class="renzheng_inf" v-if="!showResult">
			<text class="renz_f">请确保姓名、身份证号、银行卡开户人为同一人</text>
			<view class="renz_t">
				<view class="renz_item">
					<text>真实姓名</text>
					<u-input v-model="formData.realname" placeholder="请填写姓名" :border="false" class="input-field"></u-input>
				</view>
				<view class="renz_item">
					<text>证件类型</text>
					<text class="cert-type">身份证</text>
				</view>
				<view class="renz_item">
					<text>证件号</text>
					<u-input v-model="formData.id_number" placeholder="点击填写证件号" :border="false" class="input-field"></u-input>
				</view>
			</view>
			<view class="renz_t" v-if="!hideBank">
				<view class="renz_item" @click="selectBank">
					<text>开户银行</text>
					<view class="bank-select">
						<text :class="formData.bank_name === '请选择' ? 'placeholder' : ''">{{ formData.bank_name }}</text>
						<u-icon name="arrow-right" size="12" color="#909090"></u-icon>
					</view>
				</view>
				<view class="renz_item">
					<text>银行卡号</text>
					<u-input v-model="formData.bank_num" placeholder="请填写储蓄卡号" :border="false" class="input-field" @input="formatBankNo"></u-input>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="annotation" v-if="!showResult">
			<u-button type="primary" @click="submitAuth" :loading="loading" class="submit-btn">实名认证并绑定</u-button>
			<view class="note">
				<text>注:</text>
				<text>1、仅可使用储蓄卡 ,请不要填写信用卡</text>
				<text>2、仅支持开户银行列表内的30家银行</text>
			</view>
		</view>

		<!-- 认证成功页面 -->
		<view class="resultbox" v-if="showResult">
			<view class="result">
				<view class="result_inf">
					<view class="rein_img">
						<u-icon name="checkmark-circle" size="60" color="#5cb85c"></u-icon>
					</view>
					<text class="success-text">认证成功</text>
				</view>
			</view>
			<view class="renzheng_inf">
				<text class="renz_f">认证信息</text>
				<view class="renz_t">
					<view class="renz_item">
						<text>真实姓名</text>
						<text>{{ resultData.realname }}</text>
					</view>
					<view class="renz_item">
						<text>证件类型</text>
						<text>身份证</text>
					</view>
					<view class="renz_item">
						<text>证件号码</text>
						<text>{{ resultData.id_number }}</text>
					</view>
					<view class="renz_item" v-if="resultData.bank_num">
						<text>银行卡号</text>
						<text>{{ resultData.bank_num }}</text>
					</view>
				</view>
			</view>
			<u-button type="primary" @click="goNext" class="go-btn">下一步</u-button>
		</view>

		<!-- 银行选择弹窗 -->
		<u-action-sheet :show="showBankSelect" :actions="bankList" @select="onBankSelect" @close="showBankSelect = false" title="选择开户银行"></u-action-sheet>
	</view>
</template>

<script>
import { identityApi } from "@/api/index.js";

export default {
	data() {
		return {
			loading: false,
			showResult: false,
			showBankSelect: false,
			hideBank: false,
			formData: {
				realname: '',
				id_number: '',
				bank_name: '请选择',
				bank_num: ''
			},
			resultData: {
				realname: '',
				id_number: '',
				bank_num: ''
			},
			bankList: [
				{name: '锦州银行'},
				{name: '工商银行'},
				{name: '农业银行'},
				{name: '中国银行'},
				{name: '建设银行'},
				{name: '邮政储蓄银行'},
				{name: '交通银行'},
				{name: '中信银行'},
				{name: '光大银行'},
				{name: '华夏银行'},
				{name: '民生银行'},
				{name: '广发银行'},
				{name: '平安银行'},
				{name: '招商银行'},
				{name: '兴业银行'},
				{name: '浦发银行'},
				{name: '渤海银行'},
				{name: '恒丰银行'},
				{name: '浙商银行'},
				{name: '北京银行'},
				{name: '上海银行'},
				{name: '南京银行'},
				{name: '江苏银行'},
				{name: '徽商银行'},
				{name: '天津银行'},
				{name: '重庆银行'},
				{name: '河北银行'},
				{name: '内蒙古银行'},
				{name: '吉林银行'},
				{name: '湖北银行'},
				{name: '晋商银行'}
			]
		};
	},
	onLoad(options) {
		// 检查是否从云工作者页面跳转，如果是则隐藏银行信息
		if (options.nextpage === 'apply_cloudWorker.html') {
			this.hideBank = true;
		}
		// 获取已有认证信息
		this.getIdentityInfo();
	},
	methods: {
		// 获取身份认证信息
		async getIdentityInfo() {
			try {
				const res = await identityApi.getIdentityInfo();
				if (res.r === 0 && res.data) {
					const data = res.data;
					if (data.is_checked === 1) {
						// 已认证，显示结果页面
						this.showSuccessResult(data);
					}
				}
			} catch (error) {
				console.error('获取认证信息失败:', error);
			}
		},

		// 显示成功结果
		showSuccessResult(data) {
			this.showResult = true;
			
			// 处理身份证号显示（前后各保留一位，中间用*代替）
			let maskedIdNumber = '';
			if (data.id_number) {
				const idLen = data.id_number.length;
				maskedIdNumber = data.id_number[0] + '*'.repeat(idLen - 2) + data.id_number[idLen - 1];
			}
			
			// 处理银行卡号显示（前面用*代替，保留后4位）
			let maskedBankNum = '';
			if (data.card_num) {
				const cardLen = data.card_num.length;
				maskedBankNum = '*'.repeat(cardLen - 4) + data.card_num.substr(cardLen - 4);
				// 保持原有空格格式
				for (let i = 0; i < data.card_num.length - 4; i++) {
					if (data.card_num[i] === ' ') {
						maskedBankNum = maskedBankNum.substring(0, i) + ' ' + maskedBankNum.substring(i + 1);
					}
				}
			} else {
				maskedBankNum = '您还没有绑定银行卡';
			}
			
			this.resultData = {
				realname: data.realname || '',
				id_number: maskedIdNumber,
				bank_num: maskedBankNum
			};
		},

		// 选择银行
		selectBank() {
			this.showBankSelect = true;
		},

		// 银行选择回调
		onBankSelect(item) {
			this.formData.bank_name = item.name;
			this.showBankSelect = false;
		},

		// 格式化银行卡号（每4位加空格）
		formatBankNo() {
			let value = this.formData.bank_num.replace(/\s/g, ''); // 去除所有空格
			let formatted = '';
			for (let i = 0; i < value.length; i++) {
				if (i > 0 && i % 4 === 0) {
					formatted += ' ';
				}
				formatted += value[i];
			}
			this.formData.bank_num = formatted;
		},

		// 表单验证
		validateForm() {
			if (!this.formData.realname.trim()) {
				uni.showToast({
					title: '真实姓名不能为空',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.formData.id_number.trim()) {
				uni.showToast({
					title: '身份证号不能为空',
					icon: 'none'
				});
				return false;
			}
			
			// 身份证号格式验证
			const regIdNo = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
			if (!regIdNo.test(this.formData.id_number)) {
				uni.showToast({
					title: '身份证号码或格式不正确',
					icon: 'none'
				});
				return false;
			}
			
			if (!this.hideBank) {
				if (this.formData.bank_name === '请选择') {
					uni.showToast({
						title: '银行名称不能为空',
						icon: 'none'
					});
					return false;
				}
				
				if (!this.formData.bank_num.trim()) {
					uni.showToast({
						title: '银行卡号不能为空',
						icon: 'none'
					});
					return false;
				}
			}
			
			return true;
		},

		// 提交认证
		async submitAuth() {
			if (!this.validateForm()) {
				return;
			}
			
			this.loading = true;
			
			try {
				const url = this.hideBank ? 'staff_real_identity' : 'real_identity';
				const requestData = {
					realname: this.formData.realname,
					id_number: this.formData.id_number,
					bank_num: this.formData.bank_num.replace(/\s/g, ''), // 去除空格
					bank_name: this.formData.bank_name
				};
				
				const res = await identityApi.submitIdentity(requestData, url);
				
				if (res.r < 0) {
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				} else if (res.r === 0) {
					// 提交成功，重新获取认证信息显示结果
					await this.getIdentityInfo();
					
					// 如果是云工作者页面跳转，3秒后自动跳转
					const pages = getCurrentPages();
					const currentPage = pages[pages.length - 1];
					const options = currentPage.options;
					
					if (options.nextpage) {
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/identity/${options.nextpage.replace('.html', '')}`
							});
						}, 3000);
					}
				}
			} catch (error) {
				console.error('提交认证失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		// 下一步按钮
		goNext() {
			uni.navigateTo({
				url: '/pages/identity/apply_cloudWorker'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.wrapper {
	background-color: #EEEEEE;
	min-height: 100vh;
}

.renzheng_inf {
	font-size: 30rpx;
}

.renz_f {
	width: 100%;
	height: 79rpx;
	line-height: 79rpx;
	padding: 0 30rpx;
	background-color: #EEEEEE;
	color: #4B4B4B;
	margin-bottom: 20rpx;
}

.renz_t {
	width: 100%;
	padding: 0 30rpx;
	background-color: white;
	margin-bottom: 20rpx;
}

.renz_item {
	width: 100%;
	padding: 30rpx 0;
	border-bottom: 1px solid #E8E8E8;
	display: flex;
	align-items: center;
	justify-content: space-between;
	
	&:last-child {
		border-bottom: none;
	}
	
	text:first-child {
		color: #4B4B4B;
		flex-shrink: 0;
	}
}

.input-field {
	flex: 1;
	text-align: right;
	font-size: 30rpx;
}

.cert-type {
	color: #909090;
	font-size: 30rpx;
}

.bank-select {
	display: flex;
	align-items: center;
	gap: 10rpx;
	
	.placeholder {
		color: #B6B6B6;
	}
}

.annotation {
	width: 690rpx;
	margin: 88rpx auto 0;
}

.submit-btn {
	width: 100%;
	height: 90rpx;
	font-size: 33rpx;
	background-color: #FF2E00;
	border-radius: 10rpx;
	margin-bottom: 30rpx;
}

.note {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	
	text {
		color: #8D8D8D;
		font-size: 25rpx;
	}
}

.resultbox {
	background-color: #EEEEEE;
	min-height: 100vh;
}

.result {
	width: 100%;
	height: 360rpx;
	padding-top: 94rpx;
	background-color: #fff;
}

.result_inf {
	width: 233rpx;
	height: 173rpx;
	margin: 0 auto;
	font-size: 33rpx;
	color: #4B4B4B;
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 28rpx;
}

.success-text {
	font-size: 40rpx;
}

.go-btn {
	height: 90rpx;
	background-color: #FF1E00;
	color: #fff;
	font-size: 30rpx;
	margin: 100rpx 30rpx;
	border-radius: 10rpx;
}
</style>